//
//  XLBasicViewController.m
//  XLConversationInputView
//
//  Created by ilongge on 2022/8/12.
//
#import "XLCIViewResourcesManager.h"
#import "XLBasicViewController.h"
#import "XLConversationInputViewDef.h"

@interface XLBasicViewController ()
{
    ///是否需要隐藏导航栏
    BOOL _needHiddenNaviBar;
    ///是否需要动画隐藏导航栏
    BOOL _hiddenNaviBarAnimation;
}
@end

@implementation XLBasicViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (nibBundleOrNil) {
        return [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    }
    else{
        return [super initWithNibName:nibNameOrNil bundle:[XLCIViewResourcesManager XLCIResourcesBundle]];
    }
}
- (void)leftBackAction
{
    NSArray *vcArray = [self.navigationController viewControllers];
    if (vcArray.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *left = [XLCIViewResourcesManager imageNamed:@"icon_返回"];
    self.navigationItem.title = self.titleString;
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithImage:left style:UIBarButtonItemStyleDone target:self action:@selector(leftBackAction)];
    item.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = item;
    ///取消导航栏模糊层
    self.navigationController.navigationBar.translucent = NO;
    //默认不隐藏导航栏
    _needHiddenNaviBar = NO;
    _hiddenNaviBarAnimation = YES;
    //设置顶部状态栏占位取消
    self.edgesForExtendedLayout = UIRectEdgeNone;
    //适配iOS 11
    [self adjustScrollViewSafeAreaOf:self.view];
}
#pragma mark - Unified view style method

- (void)adjustScrollViewSafeAreaOf:(UIView *)superView
{
    if (@available(iOS 11.0, *)) {
        
        for (UIView *view in superView.subviews) {
            
            if ([view isKindOfClass:[UIScrollView class]]) {
                
                ((UIScrollView *)view).contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
                
                if ([view isKindOfClass:[UITableView class]]) {
                    ((UITableView *)view).estimatedRowHeight = 0;
                    ((UITableView *)view).estimatedSectionFooterHeight = 0;
                    ((UITableView *)view).estimatedSectionHeaderHeight = 0;
                }
                
            }else if (view.subviews.count > 0){
                
                [self adjustScrollViewSafeAreaOf:view];
            }
        }
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //处理导航栏是否显示
    [self setNeedHiddenNaviBar:_needHiddenNaviBar
                  andAnimation:_hiddenNaviBarAnimation];
}

///设置是否需要隐藏导航栏
-(void)setNeedHiddenNaviBar:(BOOL)isHidden
               andAnimation:(BOOL)isAnimation
{
    BOOL isCurNavHidden = self.navigationController.isNavigationBarHidden;
    if (isHidden) {
        //导航栏如果已经隐藏，不需要重复设置
        if (!isCurNavHidden) {
            [self.navigationController setNavigationBarHidden:isHidden animated:isAnimation];
        }
    }
    else{
        //导航栏已经显示，不需要重复设置
        if (isCurNavHidden) {
            
            [self.navigationController setNavigationBarHidden:isHidden animated:isAnimation];
        }
    }
}
#pragma mark - NavBarNeedHidden
///设置通用属性
- (void)naviBarNeedHidden:(BOOL)isHidden
             andAnimation:(BOOL)isAnimation
{
    _needHiddenNaviBar = isHidden;
    _hiddenNaviBarAnimation = isAnimation;
}

- (BOOL)shouldAutorotate {
    return NO;
}

#pragma mark - SetNavBarItem
- (void)setNavTitle:(NSString *)titleStr
     leftButtonItem:(UIButton *)leftBtn
    rightButtonItem:(UIButton *)rightBtn
{
    
    self.title = titleStr;
    
    UIBarButtonItem *rightBarItem = nil;
    UIBarButtonItem *rightNegativeSpacer = nil;
    
    if (rightBtn) {
        
        rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
        rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -15);
        rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0,0, -15);
        
        rightBarItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
        rightNegativeSpacer = [[UIBarButtonItem alloc]
                               initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                               target:nil action:nil];
        rightNegativeSpacer.width = -15;
        
        self.navigationItem.rightBarButtonItems = @[rightBarItem];
        
    }else{
        
        self.navigationItem.rightBarButtonItems = nil;
    }
    
    UIBarButtonItem *leftBackItem = nil;
    UIBarButtonItem *leftNegativeSpacer = nil;
    
    if (leftBtn) {
        
        leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -10,0, 0);
        leftBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -27,0, 0);
        
        leftBackItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
        leftNegativeSpacer = [[UIBarButtonItem alloc]
                              initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                              target:nil action:nil];
        leftNegativeSpacer.width = -15;
        
        self.navigationItem.leftBarButtonItems = @[leftBackItem];
    }else{
        
        self.navigationItem.leftBarButtonItems = nil;
    }
}
/// 默认样式的返回barItem按钮
- (UIButton *)normalBackButton
{
    UIButton *button = [self customBarItemButton:nil
                                 backgroundImage:nil
                                      foreground:@"icon_返回"
                                             sel:@selector(leftBackAction)];
    return button;
}

/// 自定义barItem按钮
- (UIButton *)customBarItemButton:(NSString *)title
                  backgroundImage:(NSString *)bgImg
                       foreground:(NSString *)fgImg
                              sel:(SEL)sel {
    
    UIButton *customBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIFont *font = [UIFont fontWithName:kXLCIPingFangSC_Regular
                                   size:15.0];
    
    
    CGFloat titleWidth = [self getString:title
                                andWidth:[UIFont fontWithName:kXLCIPingFangSC_Regular size:15.0]
                               andHeight:44];
    
    if (!title ||
        [title isEqualToString:@""] ||
        titleWidth < 44) {
        
        titleWidth = 44;
        
    }
    
    [customBtn setContentEdgeInsets:UIEdgeInsetsMake(0,
                                                     0,
                                                     0,
                                                     0)];
    
    
    [customBtn setFrame:CGRectMake(0,
                                   0,
                                   titleWidth+8,
                                   44)];
    [customBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [customBtn setBackgroundColor:[UIColor clearColor]];
    [customBtn setTitleShadowColor:[UIColor clearColor]
                          forState:UIControlStateNormal];
    [customBtn.titleLabel setLineBreakMode:NSLineBreakByWordWrapping];
    [customBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    
    if (bgImg) {
        UIImage *image = [XLCIViewResourcesManager imageNamed:bgImg];
        [customBtn setBackgroundImage:image forState:UIControlStateNormal];
    }
    
    if (fgImg) {
        
        [customBtn setImage:[XLCIViewResourcesManager imageNamed:fgImg]
                   forState:UIControlStateNormal];
    }
    
    if (title) {
        
        [customBtn setTitle:title forState:UIControlStateNormal];
    }
    
    [customBtn.titleLabel setFont:font];
    [customBtn setTitleColor:[UIColor blackColor]
                    forState:UIControlStateNormal];
    
    if (sel) {
        [customBtn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    }
    
    return customBtn;
}

-(CGFloat)getString:(NSString *)title andWidth:(UIFont*)font andHeight:(CGFloat)height
{
    if (title) {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:title];
        NSDictionary *attrSyleDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                                      font, NSFontAttributeName,
                                      nil];
        
        [attributedString addAttributes:attrSyleDict
                                  range:NSMakeRange(0, title.length)];
        CGRect stringRect = [attributedString boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                                           options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                             
                                                           context:nil];
        
        return stringRect.size.width;
    }
    return 0;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view.window endEditing:YES];
}
///自定义图片+title按钮
- (UIButton *)customBarImgAndTitle:(NSString *)title
                andNormalImageName:(NSString *)imageName
                andSelectImageName:(NSString *)selectImageName
                            andSel:(SEL)selector
{
    
    UIButton *imageTitleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [imageTitleBtn setTitle:title
                   forState:UIControlStateNormal];
    [imageTitleBtn setTitleColor:[UIColor whiteColor]
                        forState:UIControlStateNormal];
    [imageTitleBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [imageTitleBtn.titleLabel setFont:[UIFont fontWithName:kXLCIPingFangSC_Regular
                                                      size:15.0]];
    
    CGFloat titleWidth = [self getString:title
                                andWidth:[UIFont fontWithName:kXLCIPingFangSC_Regular size:15.0]
                               andHeight:44];
    
    [imageTitleBtn setTitleEdgeInsets:UIEdgeInsetsMake(1,
                                                       8,
                                                       1,
                                                       1)];
    
    
    UIImage *btnIconImg = [XLCIViewResourcesManager imageNamed:imageName];
    [imageTitleBtn setImage:btnIconImg
                   forState:UIControlStateNormal];
    
    if (selectImageName.length) {
        [imageTitleBtn setImage:[XLCIViewResourcesManager imageNamed:@""]
                       forState:UIControlStateSelected];
    }
    
    CGFloat width = titleWidth + btnIconImg.size.width + 16;
    [imageTitleBtn setFrame:CGRectMake(0,
                                       0,
                                       width,
                                       44)];
    imageTitleBtn.imageEdgeInsets = UIEdgeInsetsMake(14, (width - 18), 14, 0);
    [imageTitleBtn addTarget:self
                      action:selector
            forControlEvents:UIControlEventTouchUpInside];
    
    return imageTitleBtn;
    
}

///返回按钮barItem
- (UIButton *)backBarItemButtionWithSel:(SEL)sel
{
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(0, 0, 50, 44)];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 15);
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    [backBtn setImage:[XLCIViewResourcesManager imageNamed:@"icon_返回"]
             forState:UIControlStateNormal];
    
    
    if (sel) {
        [backBtn addTarget:self
                    action:sel
          forControlEvents:UIControlEventTouchUpInside];
    }
    
    return backBtn;
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
